<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>复选按钮的使用</title>
</head>
<body>
<h1>请选择你喜欢的水果</h1>
<input type="checkbox" name="fruits" id="apple" value="苹果">
<label for="apple">苹果</label>

<input type="checkbox" name="fruits" id="orange" value="橘子">
<label for="orange">橘子</label>

<input type="checkbox" name="fruits" id="strawberry" value="草莓">
<label for="strawberry">草莓</label>

<input type="checkbox" name="fruits" id="banana" value="香蕉">
<label for="banana">香蕉</label>

<input type="checkbox" name="fruits" id="watermelon" value="西瓜">
<label for="watermelon">西瓜</label>

<div id="results"></div>

<script !src="">
    let results = []

    let elements = document.querySelectorAll("input[type='checkbox']");
    let element = document.querySelector("#results");
    console.log(element);

    for (let i = 0; i < elements.length; i++) {
        console.log(elements[i]);

        elements[i].addEventListener(
            "click",
            () => {
                let index = -1;
                if (elements[i].checked) {
                    console.log(elements[i].value);
                    index = results.indexOf(elements[i].value)
                    if (index === -1) {
                        results.push(elements[i].value)
                        // console.log(results);
                        element.innerText = results
                    }
                } else {
                    results.splice(index, 1)
                    // console.log(results);
                    element.innerText = results
                }
            }
        )
    }


</script>
</body>
</html>